//
//  BindingCardViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/10/19.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "BindingCardViewController.h"
#import "BankCardReconize.h"
#import "NSString+Common.h"

@interface BindingCardViewController () <UITextFieldDelegate>

@end

@implementation BindingCardViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	
	
	[self buildUI];
	
}

#pragma mark ==========构建UI==========
- (void)buildUI {
	
	self.navigationItem.title = @"找回密码";
	
	self.view.backgroundColor = UISeparatedColorRGB;
	
	self.navigationItem.title = @"修改银行卡";
	
	NSArray *arr = @[@"卡号", @"开户银行", @"开户支行", @"持卡人", @"预留号码"];
	NSArray *placeArr = @[@"请输入银行卡号", @"通过银行卡号自动识别", @"请填写开户支行", @"持卡人姓名", @"请输入银行预留号码"];
	NSArray *infoArr;
	if (self.cardInfo) {
		infoArr = @[self.cardInfo.account, self.cardInfo.bank, self.cardInfo.sub_branch, self.cardInfo.cardholder, self.cardInfo.mobile];
	}
	
	
	CGFloat Y = 0.0f;
	
	CGSize size = [LZCTools textSizeWithText:@"测字数试试" font:kUHSystemFontWithSize(14)];
	for (int i = 0; i < arr.count; i++) {
		
		UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, Y, SCREEN_WIDTH, 40)];
		[self.view addSubview:bgV];
		bgV.backgroundColor = kWhiteColor;
		
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, size.width, bgV.height)];
		[bgV addSubview:label];
		label.textColor = kBlackColor;
		//        label.textAlignment = NSTextAlignmentCenter;
		label.text = arr[i];
		label.font = kUHSystemFontWithSize(14);
		
		CGFloat tfX = label.x+label.width+20;
		UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(tfX, 0, SCREEN_WIDTH-tfX, bgV.height)];
		[bgV addSubview:field];
		field.delegate = self;
		field.tag = 11+i;
		if (field.tag == 11) {
			field.keyboardType = UIKeyboardTypeNumberPad;
		}
		if (field.tag == 12) {
			//field.enabled = NO;
		}
		field.textColor = kBlackColor;
		field.placeholder = placeArr[i];
		field.clearButtonMode = UITextFieldViewModeWhileEditing;
		field.font = kUHSystemFontWithSize(14);
		
		if (i == 1 || i == 4) {
			//            field.keyboardType = UIKeyboardTypeNumberPad;
		}
		
		if (i == 2) {
			Y = Y+bgV.height+10;
		}
		else
			Y = Y+bgV.height+1;
		
		if (self.cardInfo) {
			field.text = infoArr[i];
		}
		
	}
	
	UIButton *completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[self.view addSubview:completeBtn];
	[completeBtn setTitle:@"保存" forState:UIControlStateNormal];
	[completeBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
	CGFloat btnHeight = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+SW(20);
	completeBtn.frame = CGRectMake(20, Y+20, SCREEN_WIDTH-40, btnHeight);
	completeBtn.backgroundColor = UIMainColorRGB;
	completeBtn.layer.cornerRadius = 5;
	completeBtn.layer.masksToBounds = YES;
	[completeBtn addTarget:self action:@selector(completeClick:) forControlEvents:UIControlEventTouchUpInside];
	
}
#pragma mark ===========代理方法==========
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
	if (textField.tag == 12) {
		return NO;
	}
	return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	UITextField *bankNo = [self.view viewWithTag:11];
	UITextField *bankName = [self.view viewWithTag:12];
	if (textField == bankNo) {
		bankName.text = [BankCardReconize getBankName:textField.text];
	}
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	
	UITextField *bankNo = [self.view viewWithTag:11];
	//删除的话string是@“”
	if ([string isEqualToString:@""]){
		return YES;
	}
	if (textField == bankNo) {
		return [self validateNumber:string];
	}
	else {
		return YES;
	}
}

- (BOOL)validateNumber:(NSString*)number {
	BOOL res = YES;
	NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
	int i = 0;
	while (i < number.length) {
		NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
		NSRange range = [string rangeOfCharacterFromSet:tmpSet];
		if (range.length == 0) {
			res = NO;
			break;
		}
		i++;
	}
	return res;
}


#pragma mark ===========响应方法==========
- (void)completeClick:(UIButton *)sender {
	NSLog(@"保存银行卡");
	UITextField *t1 = [self.view viewWithTag:11];
	UITextField *t2 = [self.view viewWithTag:12];
	UITextField *t3 = [self.view viewWithTag:13];
	UITextField *t4 = [self.view viewWithTag:14];
	UITextField *t5 = [self.view viewWithTag:15];
	
	NSArray *arr1 = @[t1.text, t2.text, t3.text, t4.text, t5.text];
	NSArray *arr2 = @[@"卡号不可为空", @"开户银行不可为空", @"开户支行不可为空", @"持卡人姓名不可为空", @"预留手机号不可为空"];
	
	for (int i = 0; i < arr1.count; i++) {
		if ([NSString isEmpty:arr1[i]]) {
			[self presentViewController:[LZCTools alertMessage:arr2[i]] animated:YES completion:nil];
			return;
		}
	}
	
	NSDictionary *param = @{@"bank":t2.text,
							@"sub_branch":t3.text,
							@"account":t1.text,
							@"cardholder":t4.text,
							@"mobile":t5.text};
	if (self.cardInfo) {
		NSString *url = [NSString stringWithFormat:@"%@/%ld", APIBankcards, self.cardInfo.bId];
		
		[[NetworkTool sharedTool] requestWithName:@"修改银行卡" URLString:url parameters:param method:@"PUT" callBack:^(id responseObject) {
			BankCard *model = [[BankCard alloc] init];
			[model setValuesForKeysWithDictionary:responseObject[@"data"]];
			[self presentViewController:[LZCTools alertMessage:@"修改银行卡成功"] animated:YES completion:nil];
			if (self.returnCard != nil) {
				self.returnCard(model);
			}
		}];
	}
	else {
		[[NetworkTool sharedTool] requestWithName:@"绑定银行卡" URLString:APIBankcards parameters:param method:@"POST" callBack:^(id responseObject) {
			[self.navigationController popViewControllerAnimated:YES];
			BankCard *model = [[BankCard alloc] init];
			[model setValuesForKeysWithDictionary:responseObject[@"data"]];[self presentViewController:[LZCTools alertMessage:@"添加银行卡成功"] animated:YES completion:nil];
			if (self.returnCard != nil) {
				self.returnCard(model);
			}
			
		}];
	}
	
}

- (void)returnCard:(ReturnCardBlock)block {
	self.returnCard = block;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
